﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WorkerRole.cs" company="AzureContrib (Open source library http://azurecontrib.codeplex.com)">
//   Microsoft Public License (Ms-PL)
// </copyright>
// <summary>
//   Defines the WorkerRole type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.Net;
using AzureContrib.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;

namespace AzureContrib.WindowsAzure.TestWorkerRole
{
	public class WorkerRole : ServiceRuntime.RoleEntryPoint
	{
		public override void Run()
		{
			var traceFactory = new WindowsAzureTraceFactory(TraceLevel.Verbose);
			var trace = traceFactory.Create(GetType());

			// System.Diagnostics.Trace.Listeners.RemoveAt(2);
			var i = 0;
			foreach (var listener in System.Diagnostics.Trace.Listeners)
			{
				trace.Verbose("Trace listener #{0}: {1}", ++i, listener.GetType().FullName);
			}

			var foo = new FooWorkItem(traceFactory);

			while (true)
			{
				trace.Verbose("Verbose trace");
				trace.Information("Information trace");
				trace.Warning("Warning trace");
				trace.Error("Error trace");
				foo.DoWork();

				WorkProvider.GetWork().DoWork();
				
				// Thread.Sleep(10000);
			}
		}

		public override bool OnStart()
		{
			var doStart = base.OnStart();

			ServicePointManager.DefaultConnectionLimit = 12;
			CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));
			CrashDumps.EnableCollection(true);

			var initialConfiguration = DiagnosticMonitor.GetDefaultInitialConfiguration();

			initialConfiguration.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
			initialConfiguration.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);

			try
			{
				DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", initialConfiguration);
			}
			catch (Exception e)
			{
				Console.WriteLine(e);
			}

			return doStart;
		}
	}
}